<script>
export default {
  components: {},
  props: {
    isOk: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      base: 0,
      process: 0,
      timeOut: null,
      failingTimer: null, //加载超时后的定时器
    };
  },
  created() {},
  mounted() {
    this.base = 0.3;
    this.start();
  },
  watch: {
    isOk(newVal) {
      if (newVal) {
        this.base = 3;
      }
    },
  },
  computed: {
   
  },
  methods: {
    start() {
      if (this.timeOut) {
        clearInterval(this.timeOut);
        this.timeOut = null;
      }
      this.timeOut = setInterval(this.addProcess.bind(this), 50);
    },

    addProcess() {
      this.process = Math.min(this.process + this.base, 100)

      if (this.process >= 99 && !this.isOk) {
        this.clear();

        this.failingTimer = setTimeout(() => {
          this.$emit("ontimeout");
        }, 3000);

        return;
      }

      if (this.process >= 70 && !this.isOk) {
        this.base = 0.005;
      }
      if (this.process >= 100) {
        this.accomplish();
      }
    },

    accomplish() {
      this.clear();

      setTimeout(() => {
        this.$emit("onsuccess");
      }, 500);
    },

    clear() {
      if (this.timeOut) {
        clearInterval(this.timeOut);
        this.timeOut = null;
      }

      if (this.failingTimer) {
        clearTimeout(this.failingTimer);
        this.failingTimer = null;
      }
    },

    format(process) {
        return Math.floor(process) + '%';
      }
  },
  beforeDestroy() {
    this.clear();
  },
  render() {
    return <el-progress percentage={this.process} format={this.format}></el-progress>;
  },
};
</script>
<style></style>
